# -*- coding:utf-8 -*-
# @FileName  :t16.py
# @Time      :2021/7/15 16:03
import base64
import io
import sys
import execjs
import requests
import time

from pyDes import *

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030')
session = requests.session()


def jie2(e):
    with open('youdao.js', 'r', encoding='gbk') as f:
        jstext = f.read()
    ctx = execjs.compile(jstext)
    result = ctx.call('rgbs', e, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36')
    return result


def main(e):
    kv = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest',
        'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
        'sec-ch-ua-mobile': '?0',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',
        'Origin': 'http://nmt.youdao.com',
        'Referer': 'http://nmt.youdao.com/'
    }
    bb = jie2(e)
    par = {
        'i': e,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': bb['salt'],
        'sign': bb['sign'],
        'lts': bb['ts'],
        'bv': bb['bv'],
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME'
    }
    req = session.get('http://nmt.youdao.com', headers=kv)
    print(session.cookies.items())
    ___rl__test__cookies = int(bb['ts']) + 3
    time.sleep(2)
    cookie = kv.get('Cookie')
    if not cookie:
        cookie = ''
        for key, value in session.cookies.items():
            if key and value:
                cookie += '%s=%s; ' % (key, value)
    cookie += '___rl__test__cookies=%s' % ___rl__test__cookies
    kv['Cookie'] = cookie
    r = session.post(f'http://nmt.youdao.com/translate_o?smartresult=dict&smartresult=rule', headers=kv, data=par).text
    print(kv)
    print(par)
    input(r)


if __name__ == "__main__":
    main('what')
